from machine import I2C,Pin
from ssd1306 import SSD1306_I2C
import menu

i2c = I2C(scl = Pin(16), sda=Pin(17))
oled = SSD1306_I2C(128, 64, i2c)

button_down = Pin(18, Pin.IN, Pin.PULL_UP)
button_click = Pin(13, Pin.IN, Pin.PULL_UP)

class App:
    name=""
    index=0
    def __init__(self, in_name, in_index):
        self.name = in_name
        self.index = in_index

    def drawLinearFunc(self, k, b):
        for x in range(0,129):
            oled.pixel(x,128-k*x+b,1)

    def runApp(self):
        while(button_click.value() == 0):
            pass
        print("run: "+self.name)
        
        nums = ["k=None", "b=None", "ok"]
        for i in range(0,10):
            nums.append(str(i))

        k_choices = "0"
        k_choice = nums.index("ok")+1
        while(k_choice != nums.index("ok")):
            k_mn = menu.Menu(nums)
            k_choice = k_mn.runMenu()
            while(button_click.value() == 0):
                pass
            print("k_choice: "+str(k_choice))
            if(k_choice >= nums.index("0") and k_choice <= nums.index("9")):
                k_choices = k_choices + nums[k_choice]
                nums[0] = "k="+str(int(k_choices))
                print("k_choices updated: " + k_choices)
        nums[0] = "k="+str(int(k_choices))
        
        b_choices = "0"
        b_choice = nums.index("ok")+1
        while(b_choice != nums.index("ok")):
            b_mn = menu.Menu(nums)
            b_choice = b_mn.runMenu()
            while(button_click.value() == 0):
                pass
            print("b_choice: "+str(b_choice))
            if(b_choice >= nums.index("0") and b_choice < nums.index("9")):
                b_choices = b_choices + nums[b_choice]
                nums[1] = "b="+str(int(b_choices))
                print("b_choices updated: " + b_choices)
        nums[1] = "b="+str(int(b_choices))


        print("k_choice: "+k_choices)
        print("b_choice: "+b_choices)
        k = int(k_choices)
        b = int(b_choices)

        oled.fill(0)
        # self.drawLinearFunc(k,b)

        x0 = -128/2
        x1 = 128/2
        y0 = -64/2
        y1 = 64/2
        if(k == 0):
            y0 = 0
            y1 = 0
        else:
            x0 = int((y0-b)/k)
            x1 = int((y1-b)/k)
        
        oled.draw_line(int(x0+128/2),int(64-(y0+64/2)),int(x1+128/2),int(64-(y1+64/2)),1)

        oled.text(f"y={str(k)}x+{str(b)}",1,1)
        oled.show()

        while(button_click.value() == 0):
            pass
        while(button_click.value() == 1):
            pass
